<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入授权方或被授权方名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleEdit"
          v-hasPerm="['channel_grant_edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDel"
          v-hasPerm="['channel_grant_del']"
        >删除
        </el-button>
      </el-col>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery"/>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch"/>
        </el-tooltip>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="tableDataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" prop="id" width="40" />
      <el-table-column label="品名" prop="goodsName"  width="150" />
      <el-table-column label="规格" prop="spce" width="80" />
      <el-table-column label="一级分类" prop="type1" width="80" />
      <el-table-column label="二级分类" prop="type2" width="80" />
      <el-table-column label="授权等级" prop="grantLevel" width="80" />
      <el-table-column label="配送方式" prop="deliveryMode" width="100" />
      <el-table-column label="供应商" prop="supplierName" width="200" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="170">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-hasPerm="['channel_grant_edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDel(scope.row)"
            v-hasPerm="['channel_grant_del']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加/修改授权对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px">
      <div>
        <el-row>
          <el-steps :active="active" finish-status="success">
            <el-step v-for="site in steps[grantType]" :title="site.title"></el-step>
          </el-steps>
        </el-row>
        <el-row></el-row>
        <el-row v-show='tabopen1'>
          <el-form ref="form" :model="form" :rules="rules" label-width="130px">
            <el-form-item label="品名" prop="goodsName" class="form-item-require-lable">
              <el-input v-model="form.goodsName" placeholder="请输入品名" clearable/>
            </el-form-item>
            <el-form-item label="价格 *" prop="goodsPrice">
              <el-input v-model="form.goodsPrice" placeholder="请输入价格" clearable/>
            </el-form-item>
            <el-form-item label="提报价格 *" prop="goodsCommitPrice">
              <el-input v-model="form.goodsCommitPrice" placeholder="请输入提报价格" clearable/>
            </el-form-item>
            <el-form-item label="平台露出价 *" prop="channelPrice">
              <el-input v-model="form.channelPrice" placeholder="请输入平台露出价" clearable/>
            </el-form-item>
            <el-form-item label="产品卖点描述" prop="goodsDesc">
              <el-input v-model="form.goodsDesc" placeholder="请输入产品卖点描述" clearable/>
            </el-form-item>
            <el-form-item label="授权等级 *" prop="grantLevel">
              <el-input v-model="form.grantLevel" placeholder="请输入授权等级" clearable/>
            </el-form-item>
            <el-form-item label="配送方式 *" prop="deliveryMode">
              <el-input v-model="form.deliveryMode" placeholder="请输入配送方式" clearable/>
            </el-form-item>
            <el-form-item label="运费 *" prop="freight">
              <el-input v-model="form.freight" placeholder="请输入运费" clearable/>
            </el-form-item>
            <el-form-item label="库存 *" prop="stock">
              <el-input v-model="form.stock" placeholder="请输入库存" clearable/>
            </el-form-item>
            <el-form-item label="规格 *" prop="spce">
              <el-input v-model="form.spce" placeholder="请输入规格" clearable/>
            </el-form-item>
            <el-form-item label="产品外链" prop="goodsUrl">
              <el-input v-model="form.goodsUrl" placeholder="请输入产品外链" clearable/>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" clearable/>
            </el-form-item>
            <el-form-item label="标签" prop="tags">
              <el-input v-model="form.tags" placeholder="请输入标签" clearable/>
            </el-form-item>
            <el-form-item label="一级分类 *" prop="type1">
              <el-input v-model="form.type1" placeholder="请输入一级分类" clearable/>
            </el-form-item>
            <el-form-item label="二级分类 *" prop="type2">
              <el-input v-model="form.type2" placeholder="请输入二级分类" clearable/>
            </el-form-item>
          </el-form>
        </el-row>
        <el-row v-show='tabopen2'>
          <el-form ref="formImg" :model="formImg" label-width="130px">
            <el-form-item label="授权书" prop="fileAuth">
              <el-upload class="upload-demo"
                         :headers="upload.headers"
                         :action="upload.url"
                         :disabled="upload.isUploading"
                         :on-preview="handlePreview" :on-remove="handleRemove1" :before-remove="beforeRemove" multiple
                         :on-success="handleFileSuccess1"
                         :limit="3" :on-exceed="handleExceed" :file-list="fileAuth">
                <el-button size="small" type="primary">点击上传</el-button>
                <!--                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
              </el-upload>
            </el-form-item>
            <el-form-item label="商标证书" prop="fileTrademark">
              <el-upload
                class="upload-demo"
                :headers="upload.headers"
                :action="upload.url"
                :disabled="upload.isUploading"
                :on-preview="handlePreview" :on-remove="handleRemove2" :before-remove="beforeRemove" multiple :limit="3"
                :on-success="handleFileSuccess2"
                :on-exceed="handleExceed" :file-list="fileTrademark">
                <el-button size="small" type="primary">点击上传</el-button>
                <!--                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
              </el-upload>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-hasPerm="['channel_grant_add','channel_grant_edit']">下一步
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getAccessToken} from "@/utils/auth";
  import { listProduct , addProduct , addProductImg } from "@/api/prod/adm";

  export default {
    name: "Grant",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 渠道表格数据
        tableDataList: [],
        // 日期范围
        dateRange: [],
        //品牌列表
        brandList: [],
        //渠道列表
        channelList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          current: 1,
          size: 10,
          name: undefined,
          key: undefined,
          isSys: undefined
        },
        // 显示搜索条件
        showSearch: true,
        // 表单参数
        form: {},
        formImg: {},
        // 表单校验
        rules: {
          goodsName: [
            {required: true, message: '授权名称不能为空', trigger: 'blur'}
          ],
          productName: [
            {required: true, message: '产品名称不能为空', trigger: 'blur'}
          ],
          dateRange: [
            {required: false, message: '授权时间不能为空', trigger: 'change'}
          ]
        },
        pId: 0,
        active: 0,
        grantType: 0,
        fileAuth: [],
        fileTrademark: [],
        status: ['一级授权', '二级授权', '三级授权'],
        steps: [
          [{title:"基本信息"},{title:"上传图片"}]
        ],
        tabopen1: false,
        tabopen2:true,
        // 文件上传参数
        upload: {
          // 是否显示弹出层
          open: false,
          // 弹出层标题
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getAccessToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/aliyunUpload/photoUpload"
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询渠道列表 */
      getList() {
        this.loading = true;
        listProduct(this.queryParams).then(response => {
            this.tableDataList = response.data;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
        this.getList();
      },
      // 表单重置
      reset() {
        this.fileAuth = [];
        this.fileTrademark = [];
        this.dateRange = [];
        this.form = {
          id: undefined,
          grantType: this.grantType,
          pId: undefined,
          name: undefined,
          remarks: undefined,
          fileAuth: [],
          fileTrademark: []
        };
        this.pId=0;
        this.resetForm("form");
        this.resetForm("formImg");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.current = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "";
        this.active = 0;
        this.tabopen1=true;
        this.tabopen2=false;
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 修改按钮操作 */
      handleEdit(row) {
        this.reset();
        const id = row.id || this.ids
      },
      /** 提交按钮 */
      submitForm: function () {
        switch (this.active) {
          case 0:
            this.$refs["form"].validate(valid => {
              if (valid) {
                console.log(this.form);
                this.active++;
                this.tabopen1=false;
                this.tabopen2=true;
              }
            });
            break;
          case 1:
            this.$refs["formImg"].validate(valid => {
              if (valid) {
                console.log(this.formImg);
                addProductImg(this.form).then(
                  response => {
                    if(response.code == 0){
                      this.msgWarning("图片保存成功");
                      cancel();
                    }else{
                      this.msgWarning("图片保存失败,请重试");
                    }
                  }
                );
              }
            });
            break;
        }
      },
      /** 删除按钮操作 */
      handleDel(row) {
        const ids = row.id || this.ids;
      },
      handleDatePicker(data) {
        this.form.startTime = data[0]
        this.form.endTime = data[1]
      },
      handleRemove1(file, fileList) {
        this.formImg.fileAuth = this.packageFile(fileList);
      },
      handleRemove2(file, fileList) {
        this.formImg.fileTrademark = this.packageFile(fileList);
      },
      packageFile(fileList) {
        let a = [];
        for (const f of fileList) {
          a.push({name: f.response.data.name, url: f.response.data.url});
        }
        return a;
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      // 文件上传成功处理
      handleFileSuccess1(response, file, fileList) {
        this.formImg.fileAuth = this.packageFile(fileList);
      },
      handleFileSuccess2(response, file, fileList) {
        this.formImg.fileTrademark = this.packageFile(fileList);
      }
    }
  };
</script>
